package demo.shiro;



import java.io.Serializable;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;



import demo.dao.User;


/**
 * 
 * @author HEN
 *
 */
public class MyShiroRealm extends AuthorizingRealm {
	
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		
		
		return null;
	}

	/**
	 * 认证回调函数,登录时调用.
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String accountName = token.getUsername();
		String password = new String(token.getPassword());

		// 用户名密码验证
		if (accountName != null && !"".equals(accountName)) {
			//UserService userService = BGDispatch.userService;
			User user = User.dao.findFirst(
					" select* from wb_user where username= ?",
					accountName);

			if (user != null)
				return new SimpleAuthenticationInfo(new Principal(user),
						password, accountName);
		}

		return null;
	}


	public static class Principal implements Serializable {

		private static final long serialVersionUID = 1L;
		
		private Integer id;
		private String password;
		private String name;
		

		public Principal(User user) {
			this.id = user.getInt("id");
			this.password = user.get("password");
			this.name = user.get("username");
			
		}

		public Integer getId() {
			return id;
		}

		public String getName() {
			return name;
		}
		public String getPassword() {
			return password;
		}
	

	}
}
